using System;
using SO;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Backpack
{
    public interface IBackpackSystem
    {
        public bool AddItem(ItemDataSO itemData);
        public bool RemoveItem(int id);
        public int CellCount { get; }
        public void RefreshBackpack();
    }
    public class BackpackSystem : IBackpackSystem, ICanTriggerEvent, ICanRegisterEvent
    {
        public static IBackpackSystem Instance = new BackpackSystem();

        private BackpackInventoryS0 backpackInventorySO;
        private BackpackSystem()
        {
            backpackInventorySO = Resources.Load<BackpackInventoryS0>("Data/BackpackInventoryS0");
        }

        public int CellCount { get => backpackInventorySO.itemList.Count; }

        public bool AddItem(ItemDataSO itemData)
        {
            ItemCellData itemCellData = backpackInventorySO.AddItem(itemData.id);
            if (itemCellData != null)
            {
                Debug.Log("添加成功");
                //添加成功
                //TODO : 通知表现层更新背包
                this.TriggerEvent(new UpdateItemCellEvent(itemCellData));
                return true;
            }
            return false;
        }

        public bool RemoveItem(int id)
        {
            ItemCellData itemCellData = backpackInventorySO.RemoveItem(id);
            if (itemCellData != null)
            {
                //移除成功
                //TODO : 通知表现层更新背包
                this.TriggerEvent(new UpdateItemCellEvent(itemCellData));
                return true;
            }
            return false;
        }
        public void RefreshBackpack()
        {
            for (int i = 0; i < backpackInventorySO.itemList.Count; ++i)
            {
                ItemDataSO itemDataSO = ItemConfigModel.Instance.GetData(backpackInventorySO.itemList[i].id);
                this.TriggerEvent(new UpdateItemCellEvent(new ItemCellData(backpackInventorySO.itemList[i], i)));
            }
        }



        public struct UpdateItemCellEvent
        {
            public ItemCellData itemCellData;
            public UpdateItemCellEvent(ItemCellData itemCellData)
            {
                this.itemCellData = itemCellData;
            }
        }
        public struct RemoveItemEvent
        {
            public ItemCellData itemCellData;
            public RemoveItemEvent(ItemCellData itemCellData)
            {
                this.itemCellData = itemCellData;
            }
        }
    }
}